<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !modifyByDeliverInfo.visible &&
        !modifyByPurchInfo.visible &&
        !modifyByContractInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="submit">提交</el-button>
          </template>
          <template v-slot:filter-confirm>
            <el-button :disabled="!canConfirm" @click="confirm">确认</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>

    <modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <ModifyByDeliver
      v-if="modifyByDeliverInfo.visible"
      :deliver-id="modifyByDeliverInfo.deliverId"
      :order-id="modifyByDeliverInfo.orderId"
      :receivingSourceOrderNo="modifyByDeliverInfo.receivingSourceOrderNo"
      v-model:visible="modifyByDeliverInfo.visible"
      :title="modifyByDeliverInfo.title"
      @returnModify="returnModify"
    />
    <ModifyByPurch
      v-if="modifyByPurchInfo.visible"
      :purch-id="modifyByPurchInfo.purchId"
      :order-id="modifyByPurchInfo.orderId"
      :receivingSourceOrderNo="modifyByPurchInfo.receivingSourceOrderNo"
      v-model:visible="modifyByPurchInfo.visible"
      :title="modifyByPurchInfo.title"
      @returnModify="returnModify"
    />
    <ModifyByContract
      v-if="modifyByContractInfo.visible"
      :contractId="modifyByContractInfo.contractId"
      :order-id="modifyByContractInfo.orderId"
      v-model:visible="modifyByContractInfo.visible"
      :title="modifyByContractInfo.title"
      @returnModify="returnModify"
    />

    <OrderDetail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      :source-type="detailInfo.receiveOrderSourceType"
      v-model:visible="detailInfo.visible"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <AddBydeliverOrder
      v-if="addDeliverDialog.visible"
      v-model:visible="addDeliverDialog.visible"
      @callback="addDeliverBack"
    />
    <AddByPurchOrder
      v-if="addPurchDialog.visible"
      v-model:visible="addPurchDialog.visible"
      @callback="addPurchBack"
    />
    <SelectContractStore
      v-if="addContractDialog.visible"
      v-model:visible="addContractDialog.visible"
      :query="addContractDialog.query"
      @callback="addContractBack"
    />

    <page-dialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="assetReceiving">
import { fatchTemplateByCode } from '@/api/base'
import AddBydeliverOrder from './addBydeliverOrder'
import AddByPurchOrder from './addByPurchOrder'
import modify from './modify'
import ModifyByDeliver from './modifyByDeliver'
import ModifyByPurch from './modifyByPurch'
import ModifyByContract from './modifyByContract'
import OrderDetail from './details'
import { getCurrentFiscalPeriod } from '@/api/core'
import {
  getReceiveCustomizeListPage,
  revokeReceive,
  confirmReceive,
  deleteReceive,
  submitReceive,
  receiveExcelOrderList,
  receivePrintOrderList,
  getReceiveDetailsAll,
  validateOrdersByReceive,
} from '@/api/asset'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const detailList = defineAsyncComponent(() => import('./detailList'))

const { proxy } = getCurrentInstance()

const addDeliverDialog = ref({
  visible: false,
})
const addPurchDialog = ref({
  visible: false,
})
const addContractDialog = ref({
  visible: false,
  query: {
    contractType: 1,
    sourceType: 1,
  },
})
const dialogTipsInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      deptAuth: {
        asTbName: 'receiving_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetReceiving:add'),
    },
    {
      type: 'button',
      label: '发货单导入',
      event: modifyByDeliver,
      show: proxy.$permission('assetReceiving:modifyByDeliver'),
    },
    {
      type: 'button',
      label: '采购单导入',
      event: modifyByPurch,
      show: proxy.$permission('assetReceiving:modifyByPurch'),
    },
    {
      type: 'button',
      label: '合同导入',
      event: modifyByContract,
      show: proxy.$permission('assetReceiving:modifyByContract'),
    },

    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('assetReceiving:submit'),
    },
    {
      type: 'slot',
      value: 'confirm',
      show: proxy.$permission('assetReceiving:confirm'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('assetReceiving:excelOrderList'),
    },
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('assetReceiving:printOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('assetReceiving:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },

      {
        label: '确认',
        event: confirm,
        show: proxy.$permission('assetReceiving:confirm'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('assetReceiving:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetReceiving:update'),
        ifRender: function (row) {
          return row.receiveOrderSourceType === -2 && row.status === 1
        },
      },
      {
        label: '修改', //发货单
        event: updateByDeliver,
        show: proxy.$permission('assetReceiving:update'),
        ifRender: function (row) {
          return row.receiveOrderSourceType === 18 && row.status === 1
        },
      },
      {
        label: '修改', //采购单
        event: updateByPurch,
        show: proxy.$permission('assetReceiving:update'),
        ifRender: function (row) {
          return row.receiveOrderSourceType === 0 && row.status === 1
        },
      },
      {
        label: '修改', //合同
        event: updateByContract,
        show: proxy.$permission('assetReceiving:update'),
        ifRender: function (row) {
          return row.receiveOrderSourceType === 61 && row.status === 1
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetReceiving:del'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  id: '',
  title: '',
})
const modifyByDeliverInfo = ref({
  visible: false,
  orderId: '',
  deliverId: '',
  title: '',
  receivingSourceOrderNo: '',
})
const modifyByPurchInfo = ref({
  visible: false,
  orderId: '',
  purchId: '',
  title: '',
  receivingSourceOrderNo: '',
})
const modifyByContractInfo = ref({
  visible: false,
  orderId: '',
  contractId: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  receiveOrderSourceType: '',
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const formInfoData = ref({})
const dialogInfo = ref({
  visible: false,
  type: '',
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
const canConfirm = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_receiving_order_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function remove(row = undefined) {
  deleteReceive([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '新增收货单'
  modifyInfo.value.visible = true
}
//修改
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.title = '修改收货单'
  modifyInfo.value.visible = true
}
function updateByDeliver(row) {
  //发货单修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyByDeliverInfo.value.visible = true
  modifyByDeliverInfo.value.deliverId = ''
  modifyByDeliverInfo.value.orderId = row.id
  modifyByDeliverInfo.value.title = '修改收货单'
}
function updateByPurch(row) {
  //采购单修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyByPurchInfo.value.visible = true
  modifyByPurchInfo.value.purchId = ''
  modifyByPurchInfo.value.orderId = row.id
  modifyByPurchInfo.value.title = '修改收货单'
}
function updateByContract(row) {
  //合同单修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyByContractInfo.value.visible = true
  modifyByContractInfo.value.contractId = ''
  modifyByContractInfo.value.orderId = row.id
  modifyByContractInfo.value.title = '修改收货单'
}

//提交
function submit(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  submitReceive(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//撤回
function revoke(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  revokeReceive(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//确认
function confirm(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  confirmReceive(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//发货单导入
function modifyByDeliver() {
  addDeliverDialog.value.visible = true
}
//发货单导入返回
function addDeliverBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      modifyByDeliverInfo.value.visible = true
      modifyByDeliverInfo.value.deliverId = data.id
      modifyByDeliverInfo.value.receivingSourceOrderNo = data.orderNo
      modifyByDeliverInfo.value.orderId = ''
      modifyByDeliverInfo.value.title = '新增收货单'
    }
  })
}
function modifyByContract() {
  //合同导入
  addContractDialog.value.visible = true
}
//合同导入返回
function addContractBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      modifyByContractInfo.value.visible = true
      modifyByContractInfo.value.contractId = data.id
      modifyByContractInfo.value.orderId = ''
      modifyByContractInfo.value.title = '新增收货单'
    }
  })
}

//采购单导入
function modifyByPurch() {
  addPurchDialog.value.visible = true
}
//采购单导入返回
function addPurchBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      modifyByPurchInfo.value.visible = true
      modifyByPurchInfo.value.purchId = data.id
      modifyByPurchInfo.value.receivingSourceOrderNo = data.purchNo
      modifyByPurchInfo.value.orderId = ''
      modifyByPurchInfo.value.title = '新增收货单'
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.receiveOrderSourceType = row.receiveOrderSourceType
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//打印导出
function pageInfo(obj) {
  page.value = obj
}
function handleClose() {
  dialogTipsInfo.value.visible = false
}
function checkConfirm() {
  if (dialogTipsInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogTipsInfo.value.type === 'print') {
    printList()
  }
  dialogTipsInfo.value.visible = false
  dialogTipsInfo.value.msg = ''
}
function exportExcel() {
  //导出
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'excel'
  dialogTipsInfo.value.msg = '请选择数据导出范围'
  dialogTipsInfo.value.btList[1].label = '导出'
  dialogTipsInfo.value.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogTipsInfo.value.flag,
  }
  receiveExcelOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  //打印
  dialogTipsInfo.value.visible = true
  dialogTipsInfo.value.type = 'print'
  dialogTipsInfo.value.msg = '请选择当数据打印范围'
  dialogTipsInfo.value.btList[1].label = '打印'
  dialogTipsInfo.value.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetReceiving:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogTipsInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  receivePrintOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
//清空
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetReceivingOrderList-com.slip.spd.entity.vo.asset.AssetReceivingOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getReceiveCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
